import baseUrl from './url.js'
import { wechatAuth } from '../api'
import { getToken, setToken, getOpenId } from './auth.js'

let isRefeshing = false
let requestQueue = []

function request(options) {
	return new Promise((resolve, reject) => {
		let data = options.data || {}
		if (options.url != '/wechat/auth') {
			data['token'] = getToken()
		}
		if(options.openid){
			data['openId'] = getOpenId() 
		}
		wx.request({
			url: baseUrl + options.url,
			method: options.method,
			data: data || {},
			success: res => {
				const code = res.data.code
				console.log(options.url,'===>','req:',data,'res:' ,res)
				if (code == 0) {
					resolve(res.data)
				} else if (code == 111) {
					if (!isRefeshing) {
						isRefeshing = true
						wechatAuth()
							.then(tokenRes => {
								// token过期后重新获取token
								setToken(tokenRes.data.session)
								//  并将此请求再此请求一次 
								request(options)
								// 然后将获取新token期间token过期的请求再次请求, 并将请求队列设为空
								requestQueue.forEach(item => {
									request(item.options)
								})
								requestQueue = []
							})
							.finally(() => {
								isRefeshing = false
							})
					} else {
						requestQueue.push({
							options: options
						})
					}
				} else if (code >= 107 && code != 111 && code != 500) {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						mask: true
					})
				} else {
					uni.showToast({
						title: '网络异常',
						icon: 'none',
						mask: true
					})
				}
			},
			fail(e) {
				uni.showToast({
					title:'请求超时，请检查您的网络',
					icon:'none',
					mask: true
				})
				reject(e)
			}
		})
	})
}

export default request